package cae.logic.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.log4j.Logger;

import cae.logic.util.CaeClipConfiguration;


public class CaeFileReciver implements Runnable
{
	private boolean stop = false;
	private static Logger logger = Logger.getLogger(CaeFileReciver.class);
	private ServerSocket sSocket;
	
	public CaeFileReciver() throws IOException
	{
		int port = CaeClipConfiguration.getInstance().getIProp(CaeClipConfiguration.FILE_PORT);
		sSocket = new ServerSocket(port);
	}
	
	public class ReciveFile implements Runnable
	{
		private Socket client;
		public static final int BUFFER_SIZE = 1024 * 50;
		private byte[] buffer;
		
		public ReciveFile(Socket client) {
			buffer = new byte[BUFFER_SIZE];
			this.client = client;
		}

		public void run() 
		{
			try
			{
				// OBTENGO INFO DE ARCHIVO
				ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
				CaeFileInfo fileInfo = (CaeFileInfo) ois.readObject();
				
				String path = CaeClipConfiguration.getInstance().getSProp(CaeClipConfiguration.FILE_DOWNLOAD_PATH);
				BufferedOutputStream out = 
					new BufferedOutputStream(new FileOutputStream(path+fileInfo.getName()));
				
				BufferedInputStream in = 
					new BufferedInputStream(client.getInputStream());
					
				
				int len = 0;
				while ((len = in.read(buffer)) > 0) {
					out.write(buffer, 0, len);
					// TODO PROGRESO
				}
				in.close();
				out.flush();
				out.close();
				client.close();
			}
			catch(Exception e)
			{
				logger.error("Error al recibir el archivo ", e);
			}
		}
	}

	public void run() 
	{
		while(!stop)
		{
			Socket cSocket;
			try {
				cSocket = sSocket.accept();
				new Thread(new ReciveFile(cSocket)).start();
			} catch (IOException e) {
				logger.error("Error al iniciar listener de archivos", e);
			}
			
		}
	}
}
